<template>
  <div class="register-warp">
    <div class="register-input">
      <div class="userName">
        <div class="img-warp">
          <img :src="userNameImg">
        </div>
        <input v-model="userInfo.TrueName" placeholder="请输入姓名" maxlength="12">
      </div>
      <div class="callPhone">
        <div class="img-warp">
          <img :src="callPhoneImg">
        </div>
        <input  v-model="userInfo.Mobile" placeholder="请输入手机号码" maxlength="11">
      </div>
      <div class="verification">
        <div class="img-warp">
            <img :src="verificationImg">
        </div>
        <input type="number" v-model="userInfo.SmsCode" style="width: 410rpx;" placeholder="请输入验证码" maxlength="6">
        <div class="requscode" v-show="is_dx_yz" @click="isdxyz()">获取验证码</div>
        <div class="requscode gain" v-show="!is_dx_yz">{{Codetime}}s重新获取</div>
        <div class="requscodeShade" v-if="!is_dx_yz"></div>
      </div>
      <div class="idCard">
        <div class="img-warp">
          <img :src="idNoImg">
        </div>
        <input v-model="userInfo.IDNO" placeholder="请输入身份证号" maxlength="18" minlength="15">
      </div>

      <div class="passWord">
        <div class="img-warp">
          <img :src="passWordImg">
        </div>
        <input v-model="userInfo.PassWord" type="password" maxlength="12" minlength="6" placeholder="请输入密码(6-12个字符)">
      </div>
      <div class="grade">
        <div class="img-warp">
          <img :src="gradeImg">
        </div>
        <div class="gradeSelect" @click="gradeOrSubjectFn('grade')">{{!selectGrade?'请选择学段':selectGrade}}</div>
      </div>
      <div class="subject">
        <div class="img-warp">
          <img :src="subjectImg">
        </div>
        <div class="gradeSelect" @click="gradeOrSubjectFn('subject')">{{!selectSubject?'请选择学科':selectSubject}}</div>
      </div>
      <div class="address">
        <div class="img-warp">
          <img :src="addressImg">
        </div>
        <div class="gradeSelect" @click="addressFn('city')">
          {{seletorCity.length==0?'点击选择地区(省 市 区/县)':seletorCity[0].name+'-'+seletorCity[1].name+'-'+seletorCity[2].name}}
        </div>
      </div>
      <div class="detailedAddress">
        <div class="img-warp">
          <img :src="addressImg">
        </div>
        <input v-model="userInfo.UserCompany" placeholder="请输入详细地址">
      </div>
      <p class="ifProtocol">
        <span :class="ifProtocol?'spanBack':''" @click="ifProtocolFn"></span>
        注册协议
        <text @click="showProtocal = true" style="color:#1da081">查看注册协议</text>
      </p>
    </div>
    <div class="submit" @click="submitRegister">注册</div>
    <div class="PopupSelect-warp" v-show="PopupSelectShow">
      <div class="PopupSelect">
        <demo-block v-if="ifThreeLevel">
          <van-area :area-list="areaList" @cancel="onCancel" @confirm="onConfirm" />
        </demo-block>
        <demo-block v-if="!ifThreeLevel">
          <van-picker show-toolbar :columns="loginColumn" @cancel="onCancel" @confirm="onConfirm" />
        </demo-block>
      </div>
    </div>
    <van-toast id="van-toast" />
    <van-popup :show="showProtocal"
               position="right"
               overlay-style="background-color:#FFF"
               custom-style="position:absolute;left:0;text-align:left;padding:0 40rpx 0 40rpx;font-size:30rpx;height:100%;"
               :z-index="99"
               >
        <article>
            <header>
                <h2 style="font-size:50rpx;margin-bottom:30rpx;">免责声明</h2>
            </header>
            <p>用户在使用网站的服务之前，应当仔细阅读本协议，并同意遵守本协议及网站所有规则后方可成为网站用户，一旦用户注册成功，
                则用户与我们之间自动形成协议关系，用户应当受本协议所有规则的约束。注册完成之时，你便获得了账号的使用权。保护账号安全，是你的责任。
            </p>
            <p>1.对于在本网站发布的不良图片、文字、音频、视频所存在的风险及一切后果将完全由用户本人承担，京师研究院对此不承担任何责任。
            且京师研究院有权立即予以删除，并视情节轻重予以相应的处置。</p>
            <p>2.本网站特有的标识、版面设计、编排方式等版权均属京师研究院享有，未经许可不得任意复制或转载。
            </p>
            <p>3.用户从京师研究院的服务中获得的信息，未经许可，不得任意复制或转载。
            </p>
            <p>4.本网站在尊重知识产权的条件下享有所有作品用于其它用途的使用权和优先权，包括但不限于网站、电子杂志、平面出版等，作者在本社区发布内容时视为同意本条款。
            </p>
            <p>5.用户在本网站发表的观点仅代表个人立场，与京师研究院无关，由作者本人承担一切法律责任。
            </p>
            <p>6.本协议解释权及修订权归北京京师大视野教育科技研究院所有。
            </p>
        </article>
        <div class="button-group">
            <button @click="showProtocal = false;ifProtocol = true">同意注册协议</button>
            <button @click="showProtocal = false">返回注册</button>
        </div>
        </van-popup>
  </div>
</template>
<script>
  import {
    getGrade,
    getSubject,
    GetPhoneSmsCode,
    userRegister,
    AppProvinceDataList
  } from "@/providers/service";

  export default {
    data() {
      return {
        Codetime: 60,
        is_dx_yz: true,
        ifProtocol: false,
        userInfo: {
            TrueName:'',
            Mobile:'',
            IDNO:'',
            SmsCode:'',
            PassWord:''
        },
        PopupSelectShow: false,
        allList:[],
        selectGrade: "",
        selectSubject: "",
        subjectIf: "",
        gradeList: [], //学段
        subjectList: [], //学科
        loginColumn: [],
        ifThreeLevel: false,
        showProtocal:false,//查看用户协议
        initialAreaList: [], //城市
        areaList: [],
        seletorCity: [],
        userNameImg: `${process.env.PUBLICIIMGURL}userName.gif`,
        callPhoneImg: `${process.env.PUBLICIIMGURL}callPhone.gif`,
        verificationImg: `${process.env.PUBLICIIMGURL}verification.gif`,
        passWordImg: `${process.env.PUBLICIIMGURL}passWord.gif`,
        gradeImg: `${process.env.PUBLICIIMGURL}grade.gif`,
        subjectImg: `${process.env.PUBLICIIMGURL}subject.gif`,
        addressImg: `${process.env.PUBLICIIMGURL}address.gif`,
        idNoImg:`${process.env.PUBLICIIMGURL}IDNO.gif`
      };
    },
    mounted() {
        wx.request({
        url: 'https://course.righthere.com.cn/todu-project/todu-project/Area/Area.json',
        method: 'GET',
        data: {
          data: {}
        },
        header: {
          'content-type': 'json'
        },
        success: (res) => {
          this.areaList = res.data
        },
        fail: (err) => {
          console.log(error)
        }
      })
      this.AppProvinceDataListFn();
      this.getgradeList();
      this.getsubjectList();
    },
      // 生命周期，页面卸载时触发
      onUnload(){
          this.ifProtocol = false
          this.showProtocal = false
          // 重置表单
          for(let key in this.userInfo){
              this.userInfo[key] = ''
          }
          this.selectGrade= ''
          this.selectSubject= ''
          this.seletorCity = ''
      },
    methods: {
      ifProtocolFn() {
        this.ifProtocol = !this.ifProtocol;
      },
      async getPhoneCode() {
          let phone = this.userInfo.Mobile
          let reg = /^1[3|4|5|7|8][0-9]{9}$/
          if (phone.length === 0) {
              this.$toast('您还未输入手机号码，请先输入手机号码后再获取验证码')
              return false
          } else if (!reg.test(phone)) {
              this.$toast('不是有效的手机号码')
              return false
          } else {
                  try {
                      let res = await GetPhoneSmsCode({ Mobile: this.userInfo.Mobile });
                      if(!res){
                          this.$toast('验证码已发送，请查收')
                          this.is_dx_yz = false;
                          let Codetimeyz = setInterval(() => {
                              if (this.Codetime-- <= 1) {
                                  this.Codetime = 60;
                                  this.is_dx_yz = true;
                                  clearInterval(Codetimeyz);
                              }
                          }, 1000);
                      }

                  } catch (error) {
                      console.log(error);
                  }
          }
      },
      async userRegisterFn() {
        try {
          let res = await userRegister({ ...this.userInfo });
          console.log('res',res)
          if (!res) {
            this.$toast("恭喜您注册成功，您现在可以登录学习了！");
            setTimeout( () => {
                wx.navigateTo({ url: "/pages/login/index" });
            },1000)
          }
        } catch (error) {
          console.log(error);
        }
      },
      async AppProvinceDataListFn() {
        try {
          let res = await AppProvinceDataList();
          this.initialAreaList = res;
        } catch (error) {
          console.log(error);
        }
      },
      onConfirm(value, index) {
        if (this.subjectIf == "grade") {
            this.userInfo.GradeID = this.gradeList.filter(item => item.Name === value.target.value)[0].ID
            this.selectGrade = value.target.value
            this.selectSubject = '请选择学科'
            let temp = []
            this.subjectList.filter(item =>item.GradeName === this.selectGrade).forEach(item =>{
                temp.push(item.SubjectName)
            })
            this.loginColumn = temp
        } else if (this.subjectIf == "subject") {
          this.selectSubject = value.target.value;
          let selectSubjectID = this.subjectList.filter(item => {
            return item.SubjectName == value.target.value;
          });
          this.userInfo.SubjectID = selectSubjectID[0].SubjectID;
        } else {
          this.seletorCity = value.target.values;
          let seletorProvinceID = this.initialAreaList.filter(item => {
            return item.ProvinceName == value.target.values[0].name;
          });
          this.userInfo.ProvinceID = seletorProvinceID[0].ProvinceID;

          let seletorCitylist = seletorProvinceID[0].Citylist.filter(item => {
            return item.CityName == value.target.values[1].name;
          });
          this.userInfo.CityID = seletorCitylist[0].CityID;
          let seletorDistrictlist = seletorCitylist[0].Districtlist.filter(
            item => {
              return item.DistrictName == value.target.values[2].name;
            }
          );
          this.userInfo.DistrictID = seletorDistrictlist[0].DistrictID;
        }
        this.PopupSelectShow = false;
        this.ifThreeLevel = false;
      },
      onCancel() {
        this.PopupSelectShow = false;
        this.ifThreeLevel = false;
      },
      async getgradeList() {
        try {
          let res = await getGrade();
          this.gradeList = res;
        } catch (error) {
          console.log(error);
        }
      },
      async getsubjectList() {
        try {
          let res = await getSubject();
          this.subjectList = res;
        } catch (error) {
          console.log(error);
        }
      },
      gradeOrSubjectFn(data) {
        this.subjectIf = data;
        this.PopupSelectShow = !this.PopupSelectShow;
        let dataType;
        let temp = []
        if (data == "grade") {
          this.gradeList.forEach(item => {
              temp.push(item.Name)
          })
            this.loginColumn = temp

        } else {
            if(!this.selectGrade){
                this.PopupSelectShow = false
                this.$toast('请先选择学段')
            }
        }
      },
      addressFn(data) {
        this.subjectIf = data;
        this.PopupSelectShow = true;
        this.ifThreeLevel = true;
      },

      isdxyz() {
        this.getPhoneCode();
      },
      submitRegister() {
          let userInfo = this.userInfo
          // 新增判断是否为汉字，必须大于2个字
          let regTrueName = new RegExp('^[\u4e00-\u9fa5]+$','g')
          if(!regTrueName.test(userInfo.TrueName)){
              this.$toast('用户名应为汉字')
              return false
          }
          if(userInfo.TrueName.length < 2){
              this.$toast('姓名长度必须大于2')
              return false
          }
          //手机号正则
          let regMobile = /^1[3|4|5|7|8][0-9]{9}$/
          if (!userInfo.Mobile) {
              this.$toast('手机号码不能为空')
              return false
          } else if (!regMobile.test(userInfo.Mobile)) {
              this.$toast('不是有效的手机号码')
              return false
          }
          //身份证号正则
          let regId = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
          if (!userInfo.IDNO) {
              this.$toast('身份证号不能为空')
              return false
          } else if (!regId.test(userInfo.IDNO)) {
              this.$toast('不是有效的身份证号')
              return false
          }
          //验证码
          if(!userInfo.SmsCode){
              this.$toast('验证码不能为空')
              return false
          } else if (userInfo.SmsCode.length < 6) {
              this.$toast('请输入完整的验证码')
              return false
          }
          //秘密PassWord
          if(!userInfo.PassWord){
              this.$toast('密码不能为空')
              return false
          } else if (userInfo.PassWord.length < 6) {
              this.$toast('密码长度不能小于6')
              return false
          }
          // 学段
          if(!this.selectGrade){
              this.$toast('请选择学段')
              return false
          }
         //学科
          if(this.selectSubject === '请选择学科'){
              this.$toast('请选择学科')
              return false
          }
          //地区
          if(!this.seletorCity.length){
              this.$toast('请选择地区')
              return false
          }
          // 详细地址
          if(!userInfo.UserCompany){
              this.$toast('请输入详细地址')
              return false
          }
          // 同意协议
          if (!this.ifProtocol) {
              this.$toast("请认真阅读免责申明，您同意注册协议后才可注册，请您知晓，谢谢配合！！");
              return false;
          }
        this.userRegisterFn();
      }
    }
  };
</script>
<style scope>
    .button-group{
        display:flex;
        flex:1;
    }
    .button-group button{
        width:100%;
        border:4rpx solid #FFF;
    }
  .register-input {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    height: 100%;
  }

  .spanBack {
    background: #1da081;
  }

  .register-input>div {
    width: 654rpx;
    height: 72rpx;
    border: 4rpx solid #1da081;
    border-radius: 14rpx;
    margin-top: 40rpx;
    align-items: center;
  }

  .register-input>div>input {
    width: 540rpx;
    height: 74rpx;
    font-size: 24rpx;
    padding-left: 20rpx;
    float: left;
  }

  .requscode {
    height: 72rpx;
    float: left;
    font-size: 24rpx;
    text-align: center;
    line-height: 72rpx;
    color: #1da081;
  }

  .verification {
    position: relative;
  }

  .requscodeShade {
    height: 72rpx;
    width: 140rpx;
    right: 0;
    opacity: 0.5;
    position: absolute;
  }

  .ifProtocol {
    height: 30rpx;
    width: 660rpx;
    font-size: 24rpx;
    color: #aaaaaa;
    margin-top: 16rpx;
    line-height: 30rpx;
  }

  .gradeSelect {
    width: 540rpx;
    height: 74rpx;
    font-size: 24rpx;
    padding-left: 20rpx;
    float: left;
    color: gray;
    line-height: 74rpx;
  }

  .PopupSelect-warp {
    position: fixed;
    z-index: 10;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.2);
  }

  .PopupSelect {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
  }

  .ifProtocol>span {
    display: inline-block;
    width: 20rpx;
    height: 20rpx;
    border: 2px solid #aaaaaa;
    vertical-align: -4rpx;
  }

  .ifProtocol>text {
    color: #000033;
  }

  .register-input>div>.img-warp {
    width: 84rpx;
    height: 74rpx;
    float: left;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .userName>div>img {
    width: 50rpx;
    height: 54rpx;
  }

  .callPhone>div>img {
    width: 34rpx;
    height: 54rpx;
  }

  .idCard>div>img {
    width: 34rpx;
    height: 54rpx;
  }

  .verification>div>img {
    width: 48rpx;
    height: 54rpx;
  }

  .userName>div>img {
    width: 48rpx;
    height: 50rpx;
  }

  .detailedAddress>div>img {
    width: 48rpx;
    height: 50rpx;
  }

  .passWord>div>img {
    width: 50rpx;
    height: 54rpx;
  }

  .grade>div>img {
    width: 50rpx;
    height: 54rpx;
  }

  .subject>div>img {
    width: 50rpx;
    height: 50rpx;
  }

  .address>div>img {
    width: 50rpx;
    height: 59rpx;
  }

  .submit {
    width: 660rpx;
    height: 72rpx;
    border: 4rpx;
    background: #1da081;
    text-align: center;
    line-height: 72rpx;
    border-radius: 14rpx;
    margin-top: 40rpx;
    margin: 100rpx auto;
    font-size: 32rpx;
    color: #fff;
  }


</style>
